package com.itheima.common;

import com.itheima.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>Description: 全局异常处理</p>
 *
 * @author liuyiming
 * @version 1.0.0
 * @date 2022-10-07 11:45
 */
/*@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody*/
@Slf4j
//默认捕捉带Restcontroller注解的所有类
@RestControllerAdvice
public class GlobalExceptionHandler {

    //SQL异常处理
    @ExceptionHandler(DuplicateKeyException.class)
    public R<String> exceptionHandler(DuplicateKeyException exception) {
        log.error(exception.getMessage());
        if (exception.getMessage().contains("Duplicate entry")) {
            String[] split = exception.getMessage().split(" ");
            String msg = split[9] + "已存在";
            return R.error(msg);
        } else {
            log.error("未知异常{}", exception.getMessage());
            return R.error("未知异常");
        }
    }

    //自定义异常处理
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException exception) {
        log.error(exception.getMessage());
        return R.error(exception.getMessage());
    }

    /*兜底的异常处理*/
    @ExceptionHandler(Exception.class)
    public R<String> exception(Exception e) {
        log.error("不知道什么异常，反正就是报错了，错误原因是: ", e.getMessage());
        return R.error("网络异常，请稍后再试");
    }
}
